/*
* Copyright (c) 2011 Connection Road.  All rights reserved.
* This program and the accompanying material are made available
* under the terms of the Eclipse Public Licnese v1.0 which is
* available at http://www.eclipse.org/legal/epl-v10.html
*/

using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using CrSyncFilesForms.Properties;
using CrSyncFilesForms.Utils;
using CrSyncFilesUtils;
using CrSyncFilesUtils.Enums;

namespace CrSyncFilesForms.Forms
{
    public partial class CrSyncUiPanelFolderPairInfo : UserControl
    {

        public CrSyncUiPanelFolderPairInfo(FileSyncPairInfo folderPair)
        {
            InitializeComponent();
            LoadFolderPair(folderPair);
            Init();
        }

        public CrSyncUiPanelFolderPairInfo()
        {
            InitializeComponent();
            Init();
        }

        
        public LinkLabel LinkScheduler
        {
            get { return LinkScheduleThisFolderPair; }
            set { LinkScheduleThisFolderPair = value; }
        }

        public Label LastRunDisplayString
        {
            get { return LabelLastRun; }
            set { LabelLastRun = value; }
        }

        private FileSyncPairInfo _folderPair;
        private ToolTip _toolTipLeft;
        private ToolTip _toolTipRight;

        private void Init()
        {
            // Link's tool tip
            var toolTipLinkAction = new ToolTip();
            toolTipLinkAction.SetToolTip(LinkChangeAction, Resources.TOOLTIP_CHANGE_ACTION);

            var toolTipLinkOption = new ToolTip();
            toolTipLinkOption.SetToolTip(LinkChangeOptions, Resources.TOOLTIP_CHANGE_OPTIONS);

            _toolTipLeft = new ToolTip();
            _toolTipRight = new ToolTip();
        }

        public void LoadFolderPair(FileSyncPairInfo folderPair)
        {
            _folderPair = folderPair;
            LabelFolderPairName.Text = folderPair.FolderPairName;

            LabelSourcePath.Text = folderPair.LeftFolder.Location;
            LabelSourcePath.ForeColor = Color.Black;
            LabelDestinationPath.Text = folderPair.RightFolder.Location;
            LabelDestinationPath.ForeColor = Color.Black;
            LinkChangeAction.Text = ((FolderPairActionTypeEnum) folderPair.FolderPairActionTypeId).ToString();
            var lastRun = folderPair.LastRunDisplayString;
            if ((string.IsNullOrEmpty(lastRun)) || (lastRun == ""))
            {
                LabelLastRun.Text = Resources.TEXT_NOT_RUN_YET;
            }
            else
            {
                LabelLastRun.Text = string.Format("Last run: {0}", lastRun);
            }

            // Load various display options
            DisplayOptionsForFolderPair(folderPair);

            if (folderPair.LeftFolder.Validate(folderPair, ApplicationGlobals.PairManager) !=
                CrSyncFileLocationResult.Valid)
            {
                SetMissingFolderLabel(LabelSourcePath);
                LabelSourcePath.ForeColor = Color.Red;
            }
            else
            {
                LabelSourcePath.ForeColor = Color.Black;
            }

            if (folderPair.RightFolder.Validate(folderPair, ApplicationGlobals.PairManager) !=
                CrSyncFileLocationResult.Valid)
            {
                SetMissingFolderLabel(LabelDestinationPath);
                LabelDestinationPath.ForeColor = Color.Red;
            }
            else
            {
                LabelDestinationPath.ForeColor = Color.Black;
            }

            _toolTipLeft.SetToolTip(LabelSourcePath, _folderPair.LeftFolder.Location);
            _toolTipRight.SetToolTip(LabelDestinationPath, _folderPair.RightFolder.Location);

        }

        /// <summary>
        /// Convenience method to get various information on saved options
        /// </summary>
        /// <param name="folderPair"></param>
        private void DisplayOptionsForFolderPair(FileSyncPairInfo folderPair)
        {
            if (folderPair.FileNameIncludes.Contains("*"))
            {
                OptionLabelFilesIncluded.TextString = "All files included";
                OptionLabelFilesIncluded.EnabledLook = true;
            }
            else
            {
                OptionLabelFilesIncluded.TextString = string.Format("{0} files included", folderPair.FileNameIncludes.Count);
                OptionLabelFilesIncluded.EnabledLook = folderPair.FileNameIncludes.Count >= 1;
            }

            if (folderPair.OptionsCompareFileStreams)
            {
                OptionLabelCheckFileContents.TextString = "Check file contents";
                OptionLabelCheckFileContents.EnabledLook = true;
            }
            else
            {
                OptionLabelCheckFileContents.TextString = "Do not check file contents";
                OptionLabelCheckFileContents.EnabledLook = false;
            }

            if (folderPair.FileExcludeAttrReadOnly)
            {
                OptionLabelReadOnlyExcluded.TextString = "Exclude read-only files";
                OptionLabelReadOnlyExcluded.EnabledLook = true;
            }
            else
            {
                OptionLabelReadOnlyExcluded.TextString = "Do not exclude read-only files";
                OptionLabelReadOnlyExcluded.EnabledLook = false;
            }

            if (folderPair.FileExcludeAttrHidden)
            {
                OptionLabelHiddenExcluded.TextString = "Exclude hidden files";
                OptionLabelHiddenExcluded.EnabledLook = true;
            }
            else
            {
                OptionLabelHiddenExcluded.TextString = "Do not exclude hidden files";
                OptionLabelHiddenExcluded.EnabledLook = false;
            }

            if (folderPair.FileExcludeAttrSystem)
            {
                OptionLabelSystemExcluded.TextString = "Exclude system files";
                OptionLabelSystemExcluded.EnabledLook = true;
            }
            else
            {
                OptionLabelSystemExcluded.TextString = "Do not exclude system files";
                OptionLabelSystemExcluded.EnabledLook = false;
            }

            if (folderPair.FileNameExludes.Count >= 1)
            {
                OptionLabelFilesExcluded.TextString = string.Format("{0} files excluded", folderPair.FileNameExludes.Count);
                OptionLabelFilesExcluded.EnabledLook = true;
            }
            else
            {
                OptionLabelFilesExcluded.TextString = "No files excluded";
                OptionLabelFilesExcluded.EnabledLook = false;
            }

            if (folderPair.SubDirectoryExclusionList.Count >= 1)
            {
                OptionLabelSubfoldersExcluded.TextString = string.Format("{0} subfolder(s) excluded", folderPair.SubDirectoryExclusionList.Count);
                OptionLabelSubfoldersExcluded.EnabledLook = true;
            }
            else
            {
                OptionLabelSubfoldersExcluded.TextString = "No subfolders excluded";
                OptionLabelSubfoldersExcluded.EnabledLook = false;
            }

            if (folderPair.ActiveForRunAll)
            {
                OptionLabelActiveForRunAll.TextString = "Active for the \"Run All\" action";
                OptionLabelActiveForRunAll.EnabledLook = true;
            }
            else
            {
                OptionLabelActiveForRunAll.TextString = "Not active for the \"Run All\" action";
                OptionLabelActiveForRunAll.EnabledLook = false;
            }

            if (folderPair.OptionsBackupOlderFiles)
            {
                OptionLabelOverwrittenFiles.TextString = "Save overwritten files in the Recycle Bin";
                OptionLabelOverwrittenFiles.EnabledLook = true;
            }
            else
            {
                OptionLabelOverwrittenFiles.TextString = "Do not save overwritten files in the Recycle Bin";
                OptionLabelOverwrittenFiles.EnabledLook = false;
            }

        }

        protected void CallBackChangeOptions(object sender, LinkLabelLinkClickedEventArgs e)
        {
            var changeOption = new CrSyncUiChangeOption(_folderPair);
            if (changeOption.ShowDialog(this) == DialogResult.OK)
            {
                _folderPair = changeOption.FolderPair;
                ApplicationGlobals.PairManager.UpdateFolderPair(_folderPair);
                ApplicationGlobals.SyncToyManager.UpdateFolderPair(_folderPair);
                DisplayOptionsForFolderPair(_folderPair);
                LoadFolderPair(_folderPair);
            }
        }

        private void CallBackChangeAction(object sender, LinkLabelLinkClickedEventArgs e)
        {
          
            var changeActionDialog = new CrSyncUiChangeAction(_folderPair);
            if(changeActionDialog.ShowDialog() == DialogResult.OK)
            {
                _folderPair = changeActionDialog.FolderPair;
                ApplicationGlobals.PairManager.UpdateFolderPair(_folderPair);
                ApplicationGlobals.SyncToyManager.UpdateFolderPair(_folderPair);
                LoadFolderPair(_folderPair);
            }
        }

        private void SetMissingFolderLabel(Label aLabel)
        {
            var newLabel = aLabel.Text + "     ( Missing Folder )";
            // Write to CRSyncFile's very own log file
            var logMessage = string.Format("[MISSING FOLDER] {0}", aLabel.Text);
            CrSyncFilesUtility.WriteLog(logMessage, ApplicationGlobals.CrSyncLogFilePath);

            // Also write to Windows event log
            ApplicationGlobals.WriteEventLog(logMessage, EventLogEntryType.Information);

            if (newLabel.Length > 35)
            {
                newLabel = newLabel.Substring(0, 16) + "..." + "     ( Missing Folder )";
            }

            aLabel.Text = newLabel;
        }

        private void CallBackLoad(object sender, System.EventArgs e)
        {
            // Change schedule link labels
            if ((ConfigurationManager.AppSettings["SchedulerEnabled"] != null) && (ConfigurationManager.AppSettings["SchedulerEnabled"].Equals("True")))
            {
                LinkScheduleThisFolderPair.Visible = true;
                PictureBoxScheduler.Visible = true;
            }
            else
            {
                LinkScheduleThisFolderPair.Visible = false;
                PictureBoxScheduler.Visible = false;
            }
        }
    }
}
